package com.lhsy.djcloud.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.lhsy.djcloud.common.ReturnT;
import com.lhsy.djcloud.common.SecurityConstant;
import com.lhsy.djcloud.controller.vo.EmployeeVo;
import com.lhsy.djcloud.entity.Department;
import com.lhsy.djcloud.entity.Employee;
import com.lhsy.djcloud.entity.dto.UserDto;
import com.lhsy.djcloud.service.DepartmentService;
import com.lhsy.djcloud.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wangzw
 * @since 2020-09-14
 */
@RestController
@RequestMapping("/employee")
@Api(value = "Server-API",tags = "党员管理")
public class EmployeeController extends BaseController {
    @Autowired private DepartmentService departmentService;
    @Autowired private EmployeeService employeeService;
    @ApiOperation(value = "党员列表加载/加载自己所属部门的党员信息")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public ReturnT list(@RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                        @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize,
                        @RequestParam(value = "params",required = false) String params,
                        @RequestParam(value = "deptId",required = false)Integer deptId,
                        HttpServletRequest request){
        //校验权限
        UserDto currUser = getCurrUser(request);
        //加载当前部门相关的所有党员
        Department department = currUser.getDepartment();
        List<Employee> employees = Lists.newArrayList();
        List<Integer> deptidsSearch = Lists.newArrayList();
        if (Objects.nonNull(deptId)){
            //查询当前党下的所有党小组
            Department byId = departmentService.getById(deptId);
            if (byId.getLevel() == 1){
                //查询所有的党小组
                List<Department> departments = departmentService.getByLevel(currUser.getTenantId(), 3);
                deptidsSearch  = departments.stream().map(Department::getId).collect(Collectors.toList());
            }
            if (byId.getLevel() == 2){
                List<Department> departments = departmentService.selectByPid(byId.getId());
                deptidsSearch  = departments.stream().map(Department::getId).collect(Collectors.toList());
            }
            if (CollUtil.isEmpty(deptidsSearch)){
                deptidsSearch.add(-1);
            }
        }
        PageHelper.startPage(pageNo, pageSize);

        if (currUser.getRoleName().equals(SecurityConstant.DXZ_ROLE)){
            //查询当前部门的党员
            employees = employeeService.selectByDeptIdAndSearch(department.getId(),params);
        }

        if (currUser.getRoleName().equals(SecurityConstant.DZB_ROLE)){
            List<Department> departments = departmentService.selectByPid(department.getId());
            List<Integer> depts = Lists.newArrayList();
            if (Objects.nonNull(deptId)){
                depts.add(deptId);
            }else {
                depts = departments.stream().map(Department::getId).collect(Collectors.toList());
            }
            employees = employeeService.selectByDeptIdsAndSearch(depts,params);

        }
        if (currUser.getRoleName().equals(SecurityConstant.DJG_ROLE)){
            //查询所有的党员信息
            employees = employeeService.selectByDeptIdsAndSearch(deptidsSearch,params);
        }
        employees.forEach(employee -> {
            Department department1 = departmentService.getById(employee.getDeptId());
            if (Objects.nonNull(department1)){
                Integer fid = department1.getFid();
                Department sendDepartment = departmentService.getById(fid);
                if (Objects.nonNull(sendDepartment)){
                    Integer ffid = sendDepartment.getFid();
                    Department firstDepartment = departmentService.getById(ffid);
                    if (Objects.nonNull(firstDepartment)){
                        employee.setDeptName(firstDepartment.getDeptName()+"/"+sendDepartment.getDeptName()+"/"+department1.getDeptName());
                    }
                }
            }
        });
        PageInfo<Employee> employeePageInfo = new PageInfo<>(employees);
        return ReturnT.SUCCESS(employeePageInfo);
    }

    @ApiOperation(value = "党员列表加载/加载自己所属部门的党员信息")
    @RequestMapping(value = "/listAll",method = RequestMethod.GET)
    public ReturnT listAll(HttpServletRequest request){
        //校验权限
        UserDto currUser = getCurrUser(request);
        //加载当前部门相关的所有党员
        Department department = currUser.getDepartment();
        List<Employee> employees = Lists.newArrayList();
        if (currUser.getRoleName().equals(SecurityConstant.DXZ_ROLE)){
            //查询当前部门的党员
            employees = employeeService.selectByDeptIdAndSearch(department.getId(),null);
        }

        if (currUser.getRoleName().equals(SecurityConstant.DZB_ROLE)){
            List<Department> departments = departmentService.selectByPid(department.getId());
            List<Integer> depts = departments.stream().map(Department::getId).collect(Collectors.toList());
            employees = employeeService.selectByDeptIdsAndSearch(depts,null);

        }
        if (currUser.getRoleName().equals(SecurityConstant.DJG_ROLE)){
            //查询所有的党员信息
            employees = employeeService.selectByTenantId(currUser.getTenantId());
        }
        employees.forEach(employee -> {
            Department department1 = departmentService.getById(employee.getDeptId());
            if (Objects.nonNull(department1)){
                Integer fid = department1.getFid();
                Department sendDepartment = departmentService.getById(fid);
                if (Objects.nonNull(sendDepartment)){
                    Integer ffid = sendDepartment.getFid();
                    Department firstDepartment = departmentService.getById(ffid);
                    if (Objects.nonNull(firstDepartment)){
                        employee.setDeptName(firstDepartment.getDeptName()+"/"+sendDepartment.getDeptName()+"/"+department1.getDeptName());
                    }
                }
            }
        });
        return ReturnT.SUCCESS(employees);
    }

    @ApiOperation(value = "加载当前组织下的党员")
    @RequestMapping(value = "/getListByDept/{deptId}",method = RequestMethod.GET)
    public ReturnT getList(HttpServletRequest request,@PathVariable("deptId") Integer deptId){
        UserDto currUser = getCurrUser(request);
        Department department = departmentService.getById(deptId);
        List<Employee> employees = Lists.newArrayList();
        if (department.getLevel() == 1){
            //加载所有党员
            employees = employeeService.selectByTenantId(currUser.getTenantId());
        }
        if (department.getLevel() == 2){
            List<Department> departments = departmentService.selectByPid(deptId);
            List<Integer> deptIds = departments.stream().map(Department::getId).collect(Collectors.toList());
            employees = employeeService.selectByDeptIds(deptIds);
        }
        if (department.getLevel() == 3){
            employees = employeeService.selectByDeptId(deptId);
        }
        return ReturnT.SUCCESS(employees);
    }


    @ApiOperation(value = "党员添加/只能添加自己本部门内的党员信息")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public ReturnT add(@RequestBody EmployeeVo employeeVo, HttpServletRequest request){
        //校验权限
        UserDto currUser = getCurrUser(request);
        Employee employee = new Employee();
        BeanUtil.copyProperties(employeeVo, employee);
        employee.setTenantId(currUser.getTenantId());
        employee.setDeptId(employeeVo.getDeptId());
        employee.setStatus(Boolean.TRUE);
        employee.setCreateName(currUser.getUserName());
        employee.setCreateTime(new Date());
        employeeService.save(employee);
        return ReturnT.SUCCESS;
    }

    @ApiOperation(value = "党员编辑/只能编辑自己本部门内的党员信息")
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public ReturnT edit(@RequestBody EmployeeVo employeeVo, HttpServletRequest request){
        //校验权限
        UserDto currUser = getCurrUser(request);
        Employee employee = employeeService.getById(employeeVo.getId());
        if (Objects.isNull(employee)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"党员不存在");
        }
        BeanUtil.copyProperties(employeeVo, employee, CopyOptions.create().setIgnoreNullValue(true));
        employeeService.updateById(employee);
        return ReturnT.SUCCESS;
    }

    @ApiOperation(value = "党员删除/只能删除自己本部门内的党员信息")
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.POST)
    public ReturnT delete(@PathVariable("id") Integer id, HttpServletRequest request){
        UserDto currUser = getCurrUser(request);
        Employee employee = employeeService.getById(id);
        if (Objects.isNull(employee)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"党员不存在");
        }
        employeeService.delete(id);
        return ReturnT.SUCCESS;
    }

    @ApiOperation(value = "加载员工信息")
    @RequestMapping(value = "/view/{id}",method = RequestMethod.GET)
    public ReturnT view(@PathVariable("id") Integer id, HttpServletRequest request){
        UserDto currUser = getCurrUser(request);
        Employee employee = employeeService.getById(id);
        if (Objects.isNull(employee)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"党员不存在");
        }
        Department department1 = departmentService.getById(employee.getDeptId());
        if (Objects.nonNull(department1)){
            Integer fid = department1.getFid();
            Department sendDepartment = departmentService.getById(fid);
            if (Objects.nonNull(sendDepartment)){
                Integer ffid = sendDepartment.getFid();
                Department firstDepartment = departmentService.getById(ffid);
                if (Objects.nonNull(firstDepartment)){
                    employee.setDeptName(firstDepartment.getDeptName()+"/"+sendDepartment.getDeptName()+"/"+department1.getDeptName());
                }
            }
        }
        return ReturnT.SUCCESS(employee);
    }

}

